
<template>
  <div class="box">
    <div class="content">
      <Row type='flex'
           justify='end'
           style='padding:20px'>
        <Col>
        <Button type="primary"
                @click="addpkg"
                style="width:80px;">添加</Button>
        </Col>
      </Row>
      <div class="content_list">
        <Table stripe
               :height="this.tableHeight"
               class="table-list"
               :loading="loading"
               :columns="columns7"
               :data="datalist"
               id="mygrid">
          <template slot-scope="{ row }"
                    slot="infos">
            <span>{{row.infos[0].productQty}}</span>
          </template>
          <template slot-scope="{ row }"
                    slot="sort">
            <div><span style="cursor:pointer">
                <Input v-model="row.sort"
                       :maxlength="4"
                       ref="inputValidate"
                       @on-keyup="ketupsort(row.sort,row)"
                       @on-blur="blursort(row,row.sort)" />
              </span>
              <!-- <span @click="selectsort(row,index)"
                    style="cursor:pointer"
                    v-if="!row.sortShow">{{row.sort}}</span> -->
            </div>
          </template>
          <template slot-scope="{ row }"
                    slot="action">
            <i class="iconsys icondetail"
               title="查看详情"
               @click="detailsShow(row.pkgCode)">
            </i>
            <i class="iconsys iconedit"
               title="编辑"
               @click="uptShow(row.pkgCode)">
            </i>
            <Poptip confirm
                    title="你确定要删除吗？"
                    @on-ok="ok(row.pkgId)"
                    class="poptip_del"
                    @on-cancel="cancel">
              <i class="iconsys icondel"
                 title="删除">
              </i>
            </Poptip>
          </template>
        </Table>
      </div>
      <div>
        <div class="content_page">
          <Page :total="total"
                ref="pages"
                :current="data.offset"
                @on-change="selectPage"
                :page-size="data.limit"
                @on-page-size-change="selectSize"
                class-name="page"
                show-sizer
                show-total />
        </div>
      </div>
    </div>
    <Drawer v-model="value3"
            :title="title"
            :mask-closable="true"
            class="shopDrawer"
            width="540"
            @on-close="closed">
      <Form ref="formValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="100"
            class="shopDrawer_form"
            v-if="isTrue">
        <FormItem label="兑换券名称:"
                  prop="pkgName">
          <Input v-model="formValidate.pkgName"
                 :maxlength="20"
                 placeholder="最多输入20字"
                 @on-keyup="changeName"
                 class="popupcontent_input"></Input>
        </FormItem>
        <FormItem label="兑换币数:"
                  prop="coinNum">
          <Input v-model="formValidate.coinNum"
                 placeholder="输入范围为0~9999"
                 :maxlength="4"
                 class="popupcontent_input"
                 @on-blur="pricecoinNum"
                 @on-keyup="changecoinNum"></Input>
        </FormItem>
        <FormItem label="需要另付金额:"
                  prop="pkgPrice">
          <Input v-model="formValidate.pkgPrice"
                 placeholder="输入范围为0.00~9999.99"
                 class="popupcontent_input"
                 :maxlength="7"
                 :max="9999.99"
                 @on-blur="priceBlur"
                 @on-keyup="changeprice"></Input>
        </FormItem>
        <FormItem class="shopDrawer_form_btn">
          <Button @click="handleReset"
                  style="width:72px">取消</Button>
          <Button type="primary"
                  @click="handleSubmit"
                  style="width:72px;margin-left:20px">确认</Button>
        </FormItem>
      </Form>
      <div class="shop_detail"
           v-if="!isTrue">
        <div class="shop_detail_tit">兑换券名称:{{formValidate.pkgName}}</div>
        <!-- <div class="shop_detail_tit">条形码:{{formValidate.barCode}}</div> -->
        <div class="shop_detail_tit">兑换币数:{{formValidate.coinNum}}</div>
        <div class="shop_detail_tit"> 需要另付金额:{{formValidate.pkgPrice}}</div>
        <div class="shop_detail_bottom">
          <Button @click="Reset"
                  style="width:72px">取消</Button>
          <Button type="primary"
                  @click="Submit"
                  style="width:72px;margin-left:20px;margin-right:24px;">确认</Button>
        </div>
      </div>
    </Drawer>
  </div>
</template>
<script>
import { getSalesPackageList2, updateSortList, lookSalesPackage, createSalesPackage, delSalesPackage } from '@/api/setting'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  components: { Treeselect },
  data () {
    return {
      tableHeight: 0,
      value3: false,
      defaultUrl: require('@/assets/images/default.png'),
      total: 10,
      isTrue: true,
      title: '添加商品',
      categoryName: '',
      loading: true,
      isDisabled: false,
      isDelete: true,
      data: {
        offset: 1,
        limit: 10,
        merchantId: this.$store.state.user.merchantId,
        pkgTypeList: [3],
        shopId: this.$route.query.id
      },
      giftParmas: {
        shopId: this.$route.query.id,
        'merchantId': this.$store.state.user.merchantId,
        categoryType: 1,
        parentId: 0
      },
      columns7: [
        {
          title: '兑换券名称',
          key: 'pkgName',
          align: 'center'
        },
        {
          title: '兑换币数',
          slot: 'infos',
          align: 'center'
        },
        {
          title: '需要另付金额',
          key: 'pkgPrice',
          align: 'center'
        },
        {
          title: '排序',
          key: 'sort',
          slot: 'sort',
          align: 'center'
        },
        {
          title: '创建时间',
          key: 'createTime',
          align: 'center'
        },
        {
          title: '操作',
          key: 'action',
          width: 300,
          align: 'center',
          slot: 'action'
        }
      ],
      pkgId: '',
      datalist: [
      ],
      formValidate: {
        pkgName: '', // 名称
        coinNum: '',
        pkgPrice: '',
        shopId: this.$route.query.id,
        pkgType: '3',
        status: 1,
        creator: this.$store.state.user.userName,
        merchantId: this.$store.state.user.merchantId
      },
      ruleValidate: {
        pkgName: [{ required: true, message: '兑换券名称不能为空', trigger: 'blur' }],
        pkgPrice: [{ required: true, message: '需要另付金额不能为空', trigger: 'blur' }, { required: true, message: '输入范围为0.00到9999.99之间', trigger: 'blur', pattern: /^\d{1,4}(\.\d{1,2})?$/ }],
        coinNum: [{ required: true, message: ' 兑换币数不能为空', trigger: 'blur' }, { required: true, message: '输入范围为0到999999之间', type: 'string', trigger: 'blur', pattern: /^0|[1-9][0-9]{0,5}$/ }]
      }
    }
  },
  computed: {
  },
  created () {
  },
  mounted () {
    this.getList()
    if (!this.hasPermission('moms:setting:coupon')) {
      this.$router.replace({ name: 'error_401' })
    }
  },
  methods: {
    ketupsort (sort, row) {
      var res = String(sort)
      if (sort.length === 1) {
        res = sort.replace(/[^0-9]/g, '')
      } else {
        res = sort.replace(/^(0+)|[^\d]+/g, '')
      }
      row.sort = res
    },
    selectsort (row, idx) {
      // this.selectedIndex = idx
      // row.sortShow = true
      this.datalist.forEach(ele => {
        this.$set(ele, 'sortShow', false)
      })
      this.$set(this.datalist[idx], 'sortShow', true)
      this.$nextTick(() => {
        this.$refs.inputValidate.focus()
      })
    },
    blursort (e, sort) {
      e.sortShow = false
      var res = String(sort)
      if (sort.length === 1) {
        res = res.replace(/[^0-9]/g, '')
      } else {
        res = res.replace(/^(0+)|[^\d]+/g, '')
      }
      e.sort = res
      if (e.sort) {
        updateSortList({
          shopId: this.$route.query.id,
          merchantId: this.$store.state.user.merchantId,
          pkgId: e.pkgId,
          sort: e.sort
        }).then(res => {
          if (res.data.status === 200) {
            // this.$Message.success(`套餐开启成功`)
            this.data.offset = 1
            this.data.limit = 10
            this.getList()
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
      } else {
        this.data.offset = 1
        this.data.limit = 10
        this.getList()
      }
    },
    // 失去焦点
    changeprice () {
      this.changeNum()
    },
    changeNum () {
      // 如果用户第一位输入的是小数点，则重置输入框内容
      if (this.formValidate.pkgPrice !== '' && this.formValidate.pkgPrice.substring(0, 1) === '.') {
        this.formValidate.pkgPrice = ''
      }
      this.formValidate.pkgPrice = this.formValidate.pkgPrice.replace(/^0*(0\.|[1-9])/, '$1') // 粘贴不生效
      this.formValidate.pkgPrice = this.formValidate.pkgPrice.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
      this.formValidate.pkgPrice = this.formValidate.pkgPrice.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
      this.formValidate.pkgPrice = this.formValidate.pkgPrice.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      this.formValidate.pkgPrice = this.formValidate.pkgPrice.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
      if (this.formValidate.pkgPrice.indexOf('.') < 0 && this.formValidate.pkgPrice !== '') { // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        if (this.formValidate.pkgPrice.substring(0, 1) === '0' && this.formValidate.pkgPrice.length === 2) {
          this.formValidate.pkgPrice = this.formValidate.pkgPrice.substring(1, this.formValidate.pkgPrice.length)
        }
      }
      if (this.formValidate.pkgPrice > 9999.99) {
        this.formValidate.pkgPrice = this.formValidate.pkgPrice.substring(0, 4)
      }
    },
    pricecoinNum () {
      if (/^[a-zA-Z]+$/.test(this.formValidate.coinNum)) {
        this.formValidate.coinNum = ''
      }
    },
    priceBlur () {
      this.formValidate.pkgPrice = this.formValidate.pkgPrice + ''
      this.formValidate.pkgPrice = this.formValidate.pkgPrice.replace(/[^\d.]/g, '')
      if (this.formValidate.pkgPrice === '') {
        this.formValidate.pkgPrice = ''
      } else if (this.formValidate.pkgPrice.indexOf('.') === -1) {
        this.formValidate.pkgPrice = this.formValidate.pkgPrice + '.00'
      } else if (this.formValidate.pkgPrice.indexOf('.')) {
        let ste = this.formValidate.pkgPrice.substring(this.formValidate.pkgPrice.indexOf('.') + 1)
        if (!ste) {
          this.formValidate.pkgPrice = this.formValidate.pkgPrice + '00'
        }
        if (ste.length === 1) {
          this.formValidate.pkgPrice = this.formValidate.pkgPrice + '0'
        } if (ste.length > 2) {
          this.formValidate.pkgPrice = this.formValidate.pkgPrice.substring(0, this.formValidate.pkgPrice.indexOf('.') + 3)
        }
      }
    },
    changecoinNum () {
      this.formValidate.coinNum = this.formValidate.coinNum.replace(/^[^\d]+/g, '')
      if (this.formValidate.coinNum.length > 1) {
        this.formValidate.coinNum = this.formValidate.coinNum.replace(/^(0+)|[^\d]+/g, '')
      }
    },
    // 查看
    detailsShow (pkgCode) {
      this.value3 = true
      this.isTrue = false
      this.title = '查看商品'
      lookSalesPackage({
        pkgCode: pkgCode,
        shopId: this.$route.query.id,
        'merchantId': this.$store.state.user.merchantId
      }).then(res => {
        if (res.data.status === 200) {
          this.formValidate.pkgName = res.data.data.pkgName
          this.formValidate.coinNum = res.data.data.coinNum
          this.formValidate.pkgPrice = res.data.data.pkgPrice
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    changeName () { // 过滤空格
      this.formValidate.pkgName = this.formValidate.pkgName.replace(/\s+/g, '')
    },

    selectSize (size) {
      this.data.limit = size
      this.getList()
    },
    // 获取分页列表
    getList () {
      this.loading = true
      getSalesPackageList2({ ...this.data, offset: (this.data.offset - 1) * this.data.limit }).then(res => {
        if (res.data.status === 200) {
          this.loading = false
          this.datalist = res.data.data ? res.data.data : []
          this.datalist.forEach(ele => {
            this.$set(ele, 'sortShow', false)
          })
          this.total = res.data.totalCount
          if (res.data.data && res.data.data.length >= 10) {
            this.tableHeight = 520
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    // 添加
    addpkg () {
      this.value3 = true
      this.isTrue = true
      this.title = '新增商品'
    },
    // 重置
    Reset () {
      this.value3 = false
      this.formValidate = {
        pkgName: '', // 名称
        coinNum: '',
        pkgPrice: '',
        shopId: this.$route.query.id,
        pkgType: '3',
        status: 1,
        creator: this.$store.state.user.userName,
        merchantId: this.$store.state.user.merchantId
      }
    },
    // 确认
    Submit () {
      this.value3 = false
      this.formValidate = {
        pkgName: '', // 名称
        coinNum: '',
        pkgPrice: '',
        shopId: this.$route.query.id,
        pkgType: '3',
        status: 1,
        creator: this.$store.state.user.userName,
        merchantId: this.$store.state.user.merchantId
      }
    },
    // 分页
    selectPage (page) {
      this.data.offset = page
      this.getList()
    },
    // 删除
    ok (idx) {
      if (this.isDelete) {
        if (!this.isDelete) {
          return
        }
        this.isDelete = false
        if (this.data.offset !== 1) {
          if (this.total % this.data.limit === 1) {
            this.data.offset = this.data.offset - 1
          }
        }
        setTimeout(() => {
          delSalesPackage({
            pkgId: idx,
            shopId: this.$route.query.id,
            'merchantId': this.$store.state.user.merchantId
          }).then(res => {
            this.isDelete = true
            if (res.data.status === 200) {
              this.$Message.success('删除成功')
              this.getList()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }, 200)
      }
    },
    cancel () {

    },
    closed () {
      if (this.$refs.formValidate) {
        this.$refs.formValidate.resetFields()
        // this.value3 = false
        this.formValidate = {
          pkgName: '', // 名称
          coinNum: '',
          pkgPrice: '',
          shopId: this.$route.query.id,
          pkgType: '3',
          status: 1,
          creator: this.$store.state.user.userName,
          merchantId: this.$store.state.user.merchantId
        }
      } else {
        this.formValidate = {
          pkgName: '', // 名称
          coinNum: '',
          pkgPrice: '',
          shopId: this.$route.query.id,
          pkgType: '3',
          status: 1,
          creator: this.$store.state.user.userName,
          merchantId: this.$store.state.user.merchantId
        }
      }
    },
    handleReset (name) {
      this.$refs.formValidate.resetFields()
      this.value3 = false
    },
    handleSubmit () {
      if (this.title === '新增商品') {
        this.$refs.formValidate.validate((val) => {
          if (val) {
            if (this.isDisabled) {
              return
            }
            this.isDisabled = true
            setTimeout(() => {
              createSalesPackage(this.formValidate).then(res => {
                this.isDisabled = false
                if (res.data.status === 200) {
                  this.$Message.success('新增成功')
                  this.data.offset = 1
                  this.data.limit = 10
                  this.getList()
                  this.$refs.formValidate.resetFields()
                  this.formValidate.pkgName = ''
                  this.value3 = false
                } else {
                  this.$Message.error(`${res.data.error}`)
                }
              })
            }, 200)
          }
        })
      } else {
        this.$refs.formValidate.validate((val) => {
          if (val) {
            if (this.isDisabled) {
              return
            }
            this.isDisabled = true
            setTimeout(() => {
              createSalesPackage({
                pkgName: this.formValidate.pkgName, // 名称
                coinNum: this.formValidate.coinNum,
                pkgPrice: this.formValidate.pkgPrice,
                shopId: this.$route.query.id,
                pkgType: '3',
                status: 1,
                creator: this.$store.state.user.userName,
                merchantId: this.$store.state.user.merchantId,
                pkgId: this.pkgId
              }).then(res => {
                this.isDisabled = false
                if (res.data.status === 200) {
                  this.$Message.success('编辑成功')
                  this.getList()
                  this.$refs.formValidate.resetFields()
                  this.formValidate.pkgName = ''
                  this.value3 = false
                } else {
                  this.$Message.error(`${res.data.error}`)
                }
              })
            }, 200)
          }
        })
      }
    },
    uptShow (pkgCode) {
      this.value3 = true
      this.isTrue = true
      this.title = '编辑商品'
      lookSalesPackage({
        pkgCode: pkgCode,
        shopId: this.$route.query.id,
        'merchantId': this.$store.state.user.merchantId
      }).then(res => {
        if (res.data.status === 200) {
          this.formValidate.pkgName = res.data.data.pkgName
          this.formValidate.coinNum = res.data.data.coinNum + ''
          this.formValidate.pkgPrice = res.data.data.pkgPrice + ''
          this.pkgId = res.data.data.pkgId
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    }
  }

}
</script>
<style lang="less" scoped>
.box {
  .content_page {
    height: 80px;
    line-height: 80px;
    display: flex;
    padding-right: 20px;
    flex-direction: row;
    justify-content: flex-end;
  }
  .ivu-upload {
    width: 96px;
    height: 96px;
    position: relative;
    .replace_tit {
      position: absolute;
      bottom: 0;
      width: 96px;
      opacity: 0.6;
      background: #2d8cf0;
      height: 24px;
      text-align: center;
      line-height: 24px;
      font-size: 12px;
      color: #ffffff;
      display: none;
    }
  }
  .ivu-upload:hover .replace_tit {
    display: block;
  }
}
</style>
<style>
.popupcontent_input {
  width: 280px;
}
.shopDrawer .shopDrawer_form {
  width: 380px;
  margin: auto;
  padding-top: 16px;
}
.shopDrawer .shopDrawer_form .shopDrawer_form_btn {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  padding-top: 16px;
  border-top: 1px solid #e8eaec;
}
.shopDrawer .shop_detail_bottom {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 20px;
  padding-top: 16px;
  border-top: 1px solid #e8eaec;
  text-align: right;
}
.shopDrawer .shopDrawer_form .shopDrawer_form_btn .ivu-form-item-content {
  text-align: right;
  padding-right: 24px;
}
.poptip_del .ivu-poptip-body .ivu-icon {
  left: 18px;
}
</style>
